package com.robcity.platform.component;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @Description
 * @Author zhangsong
 * @Date 2023/6/27
 **/

@WebFilter(urlPatterns = "/*", filterName = "logMdcFilter")
@Component
public class LogMdcFilter implements Filter {
    public static final String TRACE_ID = "traceId";

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean bInsertMDC = insertMDC();
        try {
            chain.doFilter(request, response);
        } finally {
            if (bInsertMDC) {
                MDC.remove(TRACE_ID);
            }
        }
    }

    @Override
    public void destroy() {
    }

    private boolean insertMDC() {
        String uniqueId = RequestContextHolder.getRequestAttributes()==null?"":RequestContextHolder.getRequestAttributes().getSessionId();
        MDC.put(TRACE_ID, uniqueId);
        return true;
    }
}
